from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

def home(request):
    return render(request,'home.html')
from app01 import models
def book_list(request):
    book_objs = models.Book.objects.all()


    return render(request,'book_list.html',locals())

def publish_list(request):
    return render(request,'publish_list.html')

def add_book(request):
    book_objs = models.Book.objects.all()
    publish_objs = models.Publish.objects.all()
    authors = models.Author.objects.all()
    if request.method == 'POST':
        print(request.POST)

        title = request.POST.get('title')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish_id = request.POST.get('publish')
        authors = request.POST.getlist('authors')
        print(authors)
        # 添加数据
        res = models.Book.objects.create(title=title,price=price,publish_date=date,publish_id=publish_id)
        print(res)
        res.authors.add(*authors)
        return redirect('/book_list/')
    return render(request,'add_book.html',locals())



def edit_data(request,id):
    book_obj = models.Book.objects.filter(pk = id).first()
    publish_objs = models.Publish.objects.all()
    authors = models.Author.objects.all()
    if request.method=='POST':
        print(request.POST)
        title = request.POST.get('title')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish_id = request.POST.get('publish')
        authors = request.POST.getlist('authors')
        # 修改数据
        models.Book.objects.filter(pk=id).update(title=title,price=price,publish_date=date,publish_id=publish_id)

        book_obj.authors.set(authors)
        return redirect('/book_list/')


    return render(request,'edit_data.html',locals())


from django.http import JsonResponse
def delete_data(request):

    back_dic = {'code':200,'msg':'删除成功'}
    print(request.POST)
    if request.method == 'POST':
        id = request.POST.get('id')
        models.Book.objects.filter(pk=id).delete()
    return JsonResponse(back_dic)

